<template>
  <div class='app-container'>
    <div class='button-container'>
      <el-button class='filter-item' type='primary' @click="addTaskModuleDislog">添加</el-button>
      <!-- <el-button class='filter-item' type='primary' @click="editTaskModuleDislog()">变更</el-button> -->
      <el-button class='filter-item' type='primary' @click="refreshData"> 刷新</el-button>
    </div>
    <div>
      <!-- 表格 -->
      <el-table ref="taskModuleTable" class="table" @selection-change="onSelectionChanged" :data="GridPageList"
                v-loading.lock="gridDataIsLoading" element-loading-text="数据加载中..." border fit highlight-current-row>
        <el-table-column align="center" label='#' width="90">
          <template slot-scope="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column label="任务模块关键字" width="300">
          <template slot-scope="scope">
            {{scope.row.taskmoduleId}}
          </template>
        </el-table-column>
        <el-table-column label="模块程序集名" width="300">
          <template slot-scope="scope">
            {{scope.row.taskmodule}}
          </template>
        </el-table-column>
        <el-table-column label="package文件包key值" width="300">
          <template slot-scope="scope">
            {{scope.row.taskmodulepackagekey}}
          </template>
        </el-table-column>
        <el-table-column label="包文件CRC校验码" width="300">
          <template slot-scope="scope">
            {{scope.row.taskmodulepackagecrc}}
          </template>
        </el-table-column>
        <el-table-column label="备注" width="248">
          <template slot-scope="scope">
            {{scope.row.taskmoduleremark}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="editTaskModuleDislog(scope.row)">编辑</el-button>
            <el-button type='danger' size='small' @click='deletemoudule(scope.$index, scope.row)'>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div v-show="!gridDataIsLoading" class="pagination-container">
      <el-pagination @size-change="onPageSizeChanged" @current-change="onPageNoChanged"
                     :current-page.sync="paginationConfig.currentQueryPage" :page-sizes="[10,20,30, 50]"
                     :page-size="paginationConfig.selectedPageSize" layout="total, sizes, prev, pager, next, jumper"
                     :total="dataCount">
      </el-pagination>
    </div>
    <!-- 新增任务 -->
    <el-dialog title='任务模块' :visible.sync='addTaskModuleDislogOpened'>
      <el-form :model="newtaskmodule" ref="taskform" :rules="rules" label-width="200px">
        <div>
          <el-form-item label='模块程序集名' prop="taskmodule">
            <el-input v-model='newtaskmodule.taskmodule' class="input"></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="18">
              <el-form-item label='package文件包key值' prop="taskmodulepackagekey">
                <el-input v-model='newtaskmodule.taskmodulepackagekey' class="key"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <el-upload class="upload-file" :action="uploadUrl" :before-upload="beforeFileUpload"
                         :on-success="handleAvatarSuccess"
                         :show-file-list="false" v-loading.lock="fileUploadLoading"
                         element-loading-text="文件上传中...">
                <el-button type="primary">上传
                  <i class="el-icon-upload el-icon--right"></i>
                </el-button>
              </el-upload>
            </el-col>
          </el-row>

          <el-form-item label='包文件CRC校验码' prop="taskmodulepackagecrc">
            <el-input v-model='newtaskmodule.taskmodulepackagecrc' class="input"></el-input>
          </el-form-item>
          <el-form-item label='备注' prop="taskmoduleremark">
            <textarea v-model='newtaskmodule.taskmoduleremark' class="textarea"></textarea>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type='primary' @click="addTaskModuleSubmit">确定</el-button>
          <el-button type='primary' @click="addTaskModulecancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import axios from 'axios';

  export default {
    name: 'plugin',
    data() {
      return {
        gridDataSource: [],
        // 当前分页数据开始index
        startIndex: 0,
        // 当前分页数据结束index
        endIndex: 0,
        currentSelectedRow: null,
        gridDataIsLoading: false,
        fileUploadLoading: false,
        addTaskModuleDislogOpened: false,
        paginationConfig: {selectedPageSize: 10, currentQueryPage: 0},
        newtaskmodule: {
          taskmoduleId: '',
          taskmodule: '',
          taskmodulepackagekey: '',
          taskmodulepackagecrc: '',
          taskmoduleremark: ''
        },
        uploadFile: '',
        rules: {
          taskmodule: [
            {required: true, trigger: 'blur', message: '模块程序集名称必填'}
          ],
          taskmodulepackagekey: [
            {required: true, trigger: 'blur', message: 'package文件包key值必填'}
          ],
          taskmodulepackagecrc: [
            {required: true, trigger: 'blur', message: '包文件CRC校验码必填'}
          ]
        }
      };
    },
    created() {
      this.refreshData();
    },
    methods: {
      /**
       * 刷新数据
       */
      refreshData() {
        this.gridDataIsLoading = true;

        let getTaskModules = this.$http.get('/TaskPlatform/TaskConfig/GetAllTaskModuleConfig').then((response) => {
          if (response.data.isSuccess) {
            this.gridDataSource = response.data.taskModuleList;
            this.paginationConfig.currentQueryPage = 1;
          }
          this.paginationConfig.currentQueryPage = 0;
        });

        this.$http.all([getTaskModules]).then(() => {
          this.gridDataIsLoading = false;
        }).catch(() => {
          this.gridDataIsLoading = false;
        });
      },
      computeDataIndex(pageNo, pageSize) {
        this.startIndex = pageSize * (pageNo - 1) + 1;
        this.endIndex = this.startIndex + pageSize;
        console.log(this.startIndex);
        console.log(this.endIndex);
      },
      /**
       * 分页变化
       */
      onPageSizeChanged(size) {
        this.paginationConfig.selectedPageSize = size;
        this.computeDataIndex(this.paginationConfig.currentQueryPage, size);
      },
      onPageNoChanged(page) {
        this.paginationConfig.currentQueryPage = page;
        this.computeDataIndex(page, this.paginationConfig.selectedPageSize);
      },
      /**
       * 表格selectchanged
       */
      onSelectionChanged(select) {
        this.currentSelectedRow = select;
      },
      /**
       * 生成随机taskmoduleid
       */
      getnewtaskmoduleid() {
        let s = [];
        let hexDigits = '0123456789abcdef';
        for (let i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = '4';
        // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = '-';

        let uuid = s.join('');
        console.log(uuid);
        return uuid;
      },
      /**
       * 新增任务
       */

      /**
       * 删除
       */
      deletemoudule(index, row) {
        console.log(row);
        let mouduleid = row.taskmoduleId;
        if (mouduleid) {
          this.$confirm('删除后,此项将不能恢复, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
              this.$http.delete('/TaskPlatform/TaskConfig/DeleteModuleConfig', {
                params: {
                  mouduleid: mouduleid
                }
              }).then((response) => {
                if (response.data.isSuccess) {
                  this.gridDataSource.splice(index, 1);
                  this.$message({
                    message: '删除成功!',
                    type: 'success'
                  });
                }
              });
            }
          );
        }
      },
      addTaskModuleDislog() {
        this.addTaskModuleDislogOpened = true;
      },
      addTaskModuleSubmit() {
        if (this.newtaskmodule.taskmoduleId !== '') {
          this.newtaskmodule.taskmoduleId = this.newtaskmodule.taskmoduleId;
        } else {
          this.newtaskmodule.taskmoduleId = this.getnewtaskmoduleid();
        }
        console.log(this.newtaskmodule);
        this.$refs.taskform.validate((valid) => {
          if (valid) {
            this.$http.post('/TaskPlatform/TaskConfig/SaveModuleConfig',
              {
                taskmoduleId: this.newtaskmodule.taskmoduleId,
                taskmodule: this.newtaskmodule.taskmodule,
                taskmodulepackagekey: this.newtaskmodule.taskmodulepackagekey,
                taskmodulepackagecrc: this.newtaskmodule.taskmodulepackagecrc,
                taskmoduleremark: this.newtaskmodule.taskmoduleremark
              }).then((response) => {
              if (response.data.isSuccess) {
                this.$message({
                  message: '操作成功!',
                  type: 'success'
                });
                if (response.data) {
                  this.gridDataSource.push(response.data.newtaskmodule);
                }
                this.newtaskmodule = {
                  taskmoduleId: '',
                  taskmodule: '',
                  taskmodulepackagekey: '',
                  taskmodulepackagecrc: '',
                  taskmoduleremark: ''
                };
                this.addTaskModuleDislogOpened = false;
                this.refreshData();
              } else {
                this.$message({
                  message: '数据提交出现错误,请稍后重试!',
                  type: 'error'
                });
              }
            }).catch(() => {
              this.$message({
                message: '数据提交出现错误,请稍后重试!',
                type: 'error'
              });
            });
          } else {
            return false;
          }
        });
      },
      addTaskModulecancel() {
        this.newtaskmodule = {
          taskmoduleId: '',
          taskmodule: '',
          taskmodulepackagekey: '',
          taskmodulepackagecrc: '',
          taskmoduleremark: ''
        };
        this.addTaskModuleDislogOpened = false;
      },
      /**
       * 变更任务
       */
      editTaskModuleDislog(row) {
        this.newtaskmodule = {
          taskmoduleId: row.taskmoduleId,
          taskmodule: row.taskmodule,
          taskmodulepackagekey: row.taskmodulepackagekey,
          taskmodulepackagecrc: row.taskmodulepackagecrc,
          taskmoduleremark: row.taskmoduleremark
        };
        this.addTaskModuleDislogOpened = true;
      },
      /**
       * 退出
       */
      quit() {
        this.$router.push({path: '/home/dashboard'});
      },
      beforeFileUpload() {
        this.fileUploadLoading = true;
      }, /**
       * 上传任务包
       */
      handleAvatarSuccess(res, file) {
        this.fileUploadLoading = false;
        console.log(res);
        if (this.newtaskmodule.taskmoduleId !== '') {
          this.newtaskmodule.taskmoduleId = this.newtaskmodule.taskmoduleId;
        } else {
          this.newtaskmodule.taskmoduleId = this.getnewtaskmoduleid();
        }
        this.newtaskmodule.taskmoduleId = this.newtaskmodule.taskmoduleId;
        this.newtaskmodule.taskmodule = res.fileName;
        this.newtaskmodule.taskmodulepackagekey = res.packageKey;
        this.newtaskmodule.taskmodulepackagecrc = res.fileCrc;
      }
    },
    computed: {
      GridPageList() {
        if (this.gridDataSource && this.gridDataSource.length > 0) {
          if (this.startIndex > 0 && this.endIndex > 0) {
            return this.gridDataSource.slice(this.startIndex - 1, this.endIndex - 1);
          } else {
            return [];
          }
        } else {
          return [];
        }
      },
      /**
       * 上传任务包
       */
      uploadUrl() {
        let jwt = this.$cookie.get('zillionossjwt');
        let url = axios.defaults.baseURL + '/TaskPlatform/UploadTaskPackage/Upload?token=' + jwt;
        console.log(url);
        return url;
      },
      dataCount() {
        if (this.gridDataSource) {
          return this.gridDataSource.length;
        } else {
          return 0;
        }
      }
    }
  };
</script>
<style>
  .title {
    width: 100%;
    padding: 15px;
    border: 1px solid gray;
    margin: 0px;
    background: GhostWhite;
  }

  .drag-header {
    width: 100%;
    padding: 10px;
    border: 1px solid gray;
    margin: 0px;
  }

  .right {
    float: right;
    padding: 10px;
  }

  .set {
    float: right;
    padding: 1px;
  }

  .textarea {
    Height: 200px;
    width: 80%;
  }

  .input {
    width: 80%;
  }

  .key {
    width: 90%;
  }

  .upload-file {
    width: 100px;
  }

  .table {
    max-height: 700px;
    overflow: auto;
  }
</style>
